// pages/goods_list/goods_list.js
import {request} from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        id: 0,
        value: "综合",
        isActive: true
      },
      {
        id: 1,
        value: "销量",
        isActive: false
      },
      {
        id: 2,
        value: "价格",
        isActive: false
      }
    ],
    tabList:[],
    total: 1,
    index: 0
  },
  //编写接口参数
  queryParams: {
    query: '',
    cid: '',
    pagenum: 1,
    pagesize: 10
  },
  tabsItemChange(e) {
    const {index} = e.detail;
    //修改源数据
    let {tabs} = this.data;
    tabs.forEach((v, i) => {
      i === index ? v.isActive = true : v.isActive = false;
    });
    this.setData({
      tabs,
      index
    });
  },
  startX: 0,
  endX: 0,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.queryParams.cid = options.cid || "";
    this.queryParams.query = options.query || "";
    this.getGoodsList();
  },
  //获取商品列表数据
  async getGoodsList() {
    const res = await request({
      url: "/goods/search",
      data: this.queryParams
    });
    // console.log(res.data.message);
    this.setData({
      //拼接之前的和拿到的
      tabList: [...this.data.tabList, ...res.data.message.goods],
      total: parseInt(res.data.message.total / this.queryParams.pagesize) + 1
      //获取商品总数
    });
    // console.log(this.data.tabList.goods);
    //关闭下拉刷新
    wx.stopPullDownRefresh();
  },
  //触底事件
  onReachBottom() {
    if (this.queryParams.pagenum >= this.data.total) {
      // console.log('没有下一页了');
      wx.showToast({
        title: '没有下一页数据了',
      })
      return ;
    }
    this.queryParams.pagenum += 1;
    // console.log(this.queryParams.pagenum);
    this.getGoodsList();
  },
  //下拉刷新事件
  onPullDownRefresh() {
    //重置数组
    this.setData({
      tabList: []
    });
    //重置页码
    this.queryParams.pagenum = 1;
    //发送请求
    this.getGoodsList();
  },
  //滑动切换页面效果
  // 页面开始滑动
  onTouchStart(e) {
    this.startX = e.changedTouches[0].pageX;
  },
  //页面结束滑动
  onTouchEnd(e) {
    //拿取结束值
    this.endX = e.changedTouches[0].pageX;
    if ( Math.abs(this.startX - this.endX) > 160 ) {
      //拿取index赋值
      e.detail.index = (this.startX - this.endX > 0 ?this.data.index + 1 : this.data.index - 1);
      //如果到达最后一页
      e.detail.index = e.detail.index === this.data.tabs.length? 0 : e.detail.index;
      //如果到第一页
      e.detail.index = e.detail.index === -1? this.data.tabs.length - 1 : e.detail.index;
      // console.log(this.data.tabs);
      this.tabsItemChange(e);
    }  
  }
})